package com.pug.config.interceptor;


import com.pug.UserServerApplication;
import com.pug.constant.PugContants;
import com.pug.pojo.KssUser;
import com.pug.result.ResultEnum;
import com.pug.result.ex.KsdValidationException;
import com.pug.service.redis.PugRedisOperator;
import com.pug.threadlocal.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/6$ 2:51$
 */
@Component
@Slf4j
public class PassportTokenInterceptor implements HandlerInterceptor, PugContants {

    @Autowired
    private PugRedisOperator redisOperator;
    @Resource
    RedisTemplate<String,KssUser> redisTemplateUser;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authUserId = request.getHeader("AuthUserId");
        //ThreadLocal 保存用户信息
        KssUser kssUser = redisTemplateUser.opsForValue().get(PUG_XQ_LOGIN_USER_INFO + authUserId);
        UserThreadLocal.put(kssUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
